﻿using HY.DataAchieve;
using HY.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace HY.Service
{
    public class BaseService
    {
        public void MigrateDatabaseToLatestVersion()
        {
            UnitOfWork unit = new UnitOfWork();
            unit.MigrateDatabaseToLatestVersion();
        }

        #region EF操作

        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="entity">实体</param>
        public int Add<T>(T entity) where T : class
        {
            using (UnitOfWork unit = new UnitOfWork())
            {
                unit.EF<T>().Add(entity);
                return unit.Commit();
            }
        }

        /// <summary>
        /// 批量添加实体
        /// </summary>
        /// <param name="entities">实体集合</param>
        public int AddRange<T>(IEnumerable<T> entities) where T : class
        {
            using (UnitOfWork unit = new UnitOfWork())
            {
                unit.EF<T>().AddRange(entities);
                return unit.Commit();
            }
        }

        /// <summary>
        /// 更新实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Update<T>(T entity) where T : class
        {
            using (UnitOfWork unit = new UnitOfWork())
            {
                unit.EF<T>().Update(entity);
                return unit.Commit();
            }
        }

        public int UpdateRange<T>(IEnumerable<T> entities) where T : class
        {
            using (UnitOfWork unit = new UnitOfWork())
            {
                unit.EF<T>().UpdateRange(entities);
                return unit.Commit();
            }
        }

        public int Delete<T>(object key) where T : class
        {
            using (UnitOfWork unit = new UnitOfWork())
            {
                unit.EF<T>().Delete(key);
                return unit.Commit();
            }
        }

        public int Delete<T>(T entity) where T : class
        {
            using (UnitOfWork unit = new UnitOfWork())
            {
                unit.EF<T>().Delete(entity);
                return unit.Commit();
            }
        }

        public int DeleteRange<T>(IEnumerable<T> entities) where T : class
        {
            using (UnitOfWork unit = new UnitOfWork())
            {
                unit.EF<T>().DeleteRange(entities);
                return unit.Commit();
            }
        }
        /// <summary>
        /// 根据ID查询数据实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public T GetById<T>(object id) where T : class
        {
            return new UnitOfWork().EF<T>().Find(id);
        }

        /// <summary>
        /// 获取所有数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public IList<T> EFGetMany<T>() where T : class
        {
            return new UnitOfWork().EF<T>().Table.ToList();
        }

        /// <summary>
        /// 根据条件获取所有数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="condition"></param>
        /// <returns></returns>
        public IList<T> EFGetMany<T>(Expression<Func<T, bool>> condition) where T : class
        {
            return new UnitOfWork().EF<T>().Table.Where(condition).ToList();
        }

        /// <summary>
        /// 根据条件获取所有数据并排序
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="condition"></param>
        /// <param name="orderBy"></param>
        /// <param name="isAsc"></param>
        /// <returns></returns>
        public IList<T> EFGetMany<T, TKey>(Expression<Func<T, bool>> condition, Expression<Func<T, TKey>> orderBy, bool isAsc) where T : class
        {
            if (isAsc)
                return new UnitOfWork().EF<T>().Table.Where(condition).OrderBy(orderBy).ToList();
            else
                return new UnitOfWork().EF<T>().Table.Where(condition).OrderByDescending(orderBy).ToList();
        }
        
        /// <summary>
        /// 获取分页数据（单字段排序）
        /// </summary>
        /// <param name="condition">查询条件</param>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">每页大小</param>
        /// <param name="orderBy">排序条件</param>
        /// <param name="isAsc">是否升序</param>
        /// <returns>IQueryable 泛型集合</returns>
        public Tuple<int, IList<T>> EFGetPageList<T, TKey>(Expression<Func<T, bool>> condition, int pageIndex, int pageSize, Expression<Func<T, TKey>> orderBy, bool isAsc) where T : class
        {
            return new UnitOfWork().EF<T>().GetPageList(condition, pageIndex, pageSize, orderBy, isAsc);
        }

        /// <summary>
        /// 获取分页数据（多字段排序）
        /// </summary>
        /// <param name="condition">查询条件</param>
        /// <param name="pageIndex">页索引</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="orderByExpression">排序条件</param>
        /// <returns></returns>
        public Tuple<int, IList<T>> EFGetPageList<T>(Expression<Func<T, bool>> condition, int pageIndex, int pageSize, params OrderByExpression[] orderByExpression) where T : class
        {
            return new UnitOfWork().EF<T>().GetPageList(condition, pageIndex, pageSize, orderByExpression);
        }

        #endregion

        #region Dapper操作
        /// <summary>
        /// dapper通用分页方法
        /// </summary>
        /// <typeparam name="T">泛型集合实体类</typeparam>
        /// <param name="tableName">表</param>
        /// <param name="fields">列</param>
        /// <param name="where">条件</param>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">当前页显示条数</param>
        /// <param name="orderBy">排序</param>
        /// <returns></returns>
        public Tuple<int, IEnumerable<T>> GetPageList<T>(string tableName, string fields, string condition, int pageIndex, int pageSize, string orderBy)
        {
            using (UnitOfWork unit = new UnitOfWork())
            {
                return unit.Dapper().GetPageList<T>(tableName, fields, condition, pageIndex, pageSize, orderBy);
            }
        }
        #endregion
        public List<SysModule> QuerySysMenuList()
        {
            UnitOfWork unit = new UnitOfWork();
            return unit.EF<SysModule>().Table.ToList();
        }

        public void AddTest()
        {
            ////先新增一个角色
            //var newRole = new SysRole { ID = Guid.NewGuid().ToString(), Name = "测试角色", CreateUser = "admin", CreateDate = DateTime.Now };
            //unit.EF<SysRole>().Add(newRole);
            ////回滚
            //unit.Rollback();
            ////再新增一个角色
            //var ohterRole = new SysRole { ID = Guid.NewGuid().ToString(), Name = Guid.NewGuid().ToString(), CreateUser = "admin", CreateDate = DateTime.Now };
            //unit.EF<SysRole>().Add(ohterRole);
            ////最后提交//测试事务回滚代码
            //unit.Commit(); 

            //var userModel = new SysUser { ID = Guid.NewGuid().ToString(), UserName = "ef", Password = "123456", CreateUser = "admin", CreateDate = DateTime.Now };
            //unit.EF<SysUser>().Add(userModel);
            //unit.Commit();

            //var userModel2 = new SysUser { ID = Guid.NewGuid().ToString(), UserName = "ef3", Password = "123456", CreateUser = "admin", CreateDate = DateTime.Now };
            //StringBuilder sb = new StringBuilder();
            //sb.Append(" insert SysUser (ID,UserName,Password,IsDisabled,IsDeleted,CreateUser,CreateDate)");
            //sb.Append(" Values ");
            //sb.Append(" (@ID,@UserName,@Password,@IsDisabled,@IsDeleted,@CreateUser,@CreateDate) ");
            //sb.Append(";");
            //unit.Dapper().Execute(sb.ToString(), userModel2);

            //var userModel = new SysUser { UserName = "ef", Password = "123456", CreateUser = "admin", CreateDate = DateTime.Now };
            //unit.EF<SysUser>().Add(userModel);

            //unit.BeginTransaction();
            //var userModel3 = new SysUser { UserName = "ef2", Password = "123456", CreateUser = "admin", CreateDate = DateTime.Now };
            //unit.EF<SysUser>().Add(userModel3);

            //var userModel4 = new SysUser { UserName = "ef4", Password = "123456", CreateUser = "admin", CreateDate = DateTime.Now };
            //sb = new StringBuilder();
            //sb.Append(" insert SysUser (UserName,Password,IsDisabled,IsDeleted,CreateUser,CreateDate)");
            //sb.Append(" Values ");
            //sb.Append(" (@UserName,@Password,@IsDisabled,@IsDeleted,@CreateUser,@CreateDate) ");
            //sb.Append(";");
            //unit.Dapper().Execute(sb.ToString(), userModel4);
            //unit.Commit();
        }
    }
}
